<?php
namespace Game\Controller;
use Think\Controller;

class MapController extends Controller{

    public function get_map_config(){
        $stage_id = I('id');
        if(!$stage_id){
            _apiReturn(0, '请输入正确的关卡ID');
        }
        // 读取stage文件夹中的对应id的json文件
        $stage_json = file_get_contents('GameConfig/stage/'.$stage_id.'.json');
        if(!$stage_json){
            _apiReturn(0, '关卡不存在');
        }
        _apiReturn(1, '获取成功', $stage_json);
    }

    public function stage_play(){
        C('LAYOUT_NAME','layout_layui');
        $stage_id = I('id');
        // 读取stage文件夹中的对应id的json文件
        $stage_json = file_get_contents('GameConfig/stage/'.$stage_id.'.json');
        // 正则转译 把<color=#ffffff>红</color>转成<span style="color:#ffffff">红</span>
        $stage_json = preg_replace('/<color=#([0-9a-fA-F]{6})>(.*?)<\/color>/', "<span style='color:#$1'>$2</span>", $stage_json);
        if(!$stage_json){
            $this->error('关卡不存在');
        }
        $stage = json_decode($stage_json,true);
        $items = $stage['items'];
        foreach($items as $k=>$v){
            $items[$k]['pos'] = $v['pos'][array_rand($v['pos'])];
            $items[$k]['x'] = $v['x'][array_rand($v['x'])];
            if($v['type'] == 'gateQuestion2'){
                if($v['params']['isRandom']){
                    $items[$k]['params']['questionList'] = $stage['config']['questionList'];
                }
                $items[$k]['params']['question'] = $items[$k]['params']['questionList'][array_rand($items[$k]['params']['questionList'])];
                $items[$k]['params']['title'] = $items[$k]['params']['question']['question'];
                $options = [
                    [
                        'result' => 'right',
                        'option' => $items[$k]['params']['question']['rightList'][array_rand($items[$k]['params']['question']['rightList'])]
                    ],
                    [
                        'result' => 'wrong',
                        'option' => $items[$k]['params']['question']['wrongList'][array_rand($items[$k]['params']['question']['wrongList'])]
                    ]
                ];
                shuffle($options);
                $items[$k]['params']['options'] = $options;
                unset($items[$k]['params']['questionList']);
                unset($items[$k]['params']['question']);
            }
        }
        $this->assign('config', $stage['config']);
        $this->assign('items', $items);
        C('LAYOUT_NAME','layout_layui');
        $this->display();
    }

    public function color(){
        // C('LAYOUT_NAME','layout_layui');
        $this->display();
    }
}